/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ambimmort.shj.action.logmanage.nn;

import cn.net.greenet.db.HibernateUtil;
import cn.net.greenet.db.bean.Ackincominglog;
import cn.net.greenet.db.bean.MessageoutgoinglogManual;
import cn.net.greenet.logmanage.nn.GetMessageType;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 程序手动下发日志查询
 *
 * @author liangdelin
 */
public class QuerySendPolicyHand {

    public static String query(String iDisplayStart, String iDisplayLength, String id, String startTime, String endTime, String MessageType, String MessageNo) {
        JSONArray jsonArr = new JSONArray();  //Data        
        long count = 0; //记录的总条数
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SessionFactory sf = HibernateUtil.getSessionFactory();
        Session session = sf.openSession();
        session.clear();
        Map<String, String> paras = new HashMap<>();
        paras.put("sendStartTime", startTime);
        paras.put("sendStopTime", endTime);
        paras.put("messageType", MessageType);
        paras.put("messageNo", MessageNo);
        Iterator<String> it = paras.keySet().iterator();
        while (it.hasNext()) {
            if ("".equals(paras.get(it.next()))) {
                it.remove();
            }
        }
        if (paras.isEmpty()) {
            return "{[]}";
        } else {
            StringBuilder hql = new StringBuilder("select log from MessageoutgoinglogManual As log where ");
            for (String key : paras.keySet()) {
                if ("sendStartTime".equals(key)) {
                    hql.append(" log.").append(key).append(">=").append(":").append(key).append(" and");
                } else if ("sendStopTime".equals(key)) {
                    hql.append(" log.").append(key).append("<=").append(":").append(key).append(" and");
                } else {
                    hql.append(" log.").append(key).append("=").append(":").append(key).append(" and");
                }
            }
            hql.delete(hql.length() - 4, hql.length());
            hql.append(" and log.dpiendpointbean.id =:id  order by log.sendStartTime desc");
            Query query = session.createQuery(hql.toString());
            for (String key : paras.keySet()) {
                if ("sendStartTime".equals(key) || "sendStopTime".equals(key)) {
                    query.setParameter(key, new Date(Long.parseLong(paras.get(key) + "000")));
                } else if ("messageNo".equals(key)) {
                    query.setParameter(key, Integer.parseInt(paras.get(key)));
                } else {
                    query.setParameter(key, paras.get(key));
                }
            }
            query.setParameter("id", Integer.parseInt(id));
            count = query.list().size();  //查询的总条数
            query.setFirstResult(Integer.parseInt(iDisplayStart));  //起始查询条数
            query.setMaxResults(Integer.parseInt(iDisplayLength));  //带页面显示的条数（步长）
            List l = query.list();
            for (Object o : l) {
                MessageoutgoinglogManual messageOut = (MessageoutgoinglogManual) o;
                Query q = session.createQuery("select ack from Ackincominglog as ack where ack.messageType =:messageType and ack.messageNo =:messageNo and ack.messageSequenceNo =:messageSequenceNo");
                q.setParameter("messageType", messageOut.getMessageType());
                q.setParameter("messageNo", messageOut.getMessageNo());
                q.setParameter("messageSequenceNo", messageOut.getMessageSequenceNo());
                JSONArray joArr = new JSONArray();
                joArr.add(messageOut.getId()+"");
                joArr.add(messageOut.getDpiendpointbean().getName()); //设备名称
                joArr.add(GetMessageType.getMessageType().get(messageOut.getMessageType()));  //MessageType
                joArr.add(messageOut.getMessageNo()); //MessageNo
                joArr.add(messageOut.getMessageSequenceNo()); //MessageSequenceNo
//                joArr.add(messageOut.getMessageSerialNo());  //MessageSerialNo
                joArr.add(format.format(messageOut.getSendStartTime()));  //下发策略的起始时间
                joArr.add(format.format(messageOut.getSendStopTime()));  //下发策略的结束时间
                joArr.add(messageOut.isIsSentSuccess() ? "成功" : "失败");  //策略下发是否成功
                List ack = q.list();
                if (ack.isEmpty()) //无Ack  
                {
                    joArr.add("未收到");  //未收到Ack
                    joArr.add("--"); // Ack收到的时间

                } else // 有Ack
                {
                    Ackincominglog ackLog = (Ackincominglog) ack.get(0);
                    joArr.add("收到");  //收到Ack
                    joArr.add(format.format(ackLog.getReceiveTime()));
                }
                jsonArr.add(joArr);
            }
        }
        JSONObject jo = new JSONObject();
        jo.put("iTotalRecords", count);
        jo.put("iTotalDisplayRecords", count);
        jo.put("aaData", jsonArr);
        session.close();
        return jo.toString();
    }
}
